import Request from "luch-request"

import
useLoginStore from "@/store/login.js"
// 实例化网络请求
const luoReuqest = new Request({
	baseURL: "https://consult-api.itheima.net",
	custom: {
		loading: true
	}
})

const tabBarList = ["pages/index/index", "pages/wiki/wiki", "pages/my/my", "pages/notify/notify"]

const whiteList = [
	"/code",
	"/login",
	"login/password"
]

//  请求拦截器
luoReuqest.interceptors.request.use((config) => {
	if (config.custom.loading) {
		uni.showLoading({
			title: "正在加载...",
			mask: true
		})
	}
	const loginStore = useLoginStore()
	const defaultHeader = {}

	if (loginStore.token && !whiteList.includes(config.url)) {
		defaultHeader.Authorization = "Bearer " + loginStore.token
	}

	config.header = {
		...defaultHeader,
		...config.header
	}
	return config
}, (err) => {
	return new Promise.reject(err)
})

luoReuqest.interceptors.response.use((res) => {
	// 关闭提示
	uni.hideLoading()
	return res.data
}, (error) => {
	// 关闭提示
	uni.hideLoading()
	if (error.statusCode == 401) reLogin()
	return new Promise.reject(error)
})


function reLogin() {
	// 获取当前页面
	const pageStack = getCurrentPages()
	console.log(pageStack);
	const currentPage = pageStack[pageStack.length - 1]

	const redirectURL = currentPage.$page.fullPath

	const openType = tabBarList.includes(currentPage.route) ? "switchTab" : "redirectTo"

	const loginStore = useLoginStore()

	loginStore.recirectURL = redirectURL
	loginStore.openType = openType


	uni.redirectTo({
		url: "/pages/login/login"
	});
}
export {
	luoReuqest
}